package com.bjb.vr.common.service;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.ao.ResCusContentAuthorityAo;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.*;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.mapper.ResContentAuthorityMapper;
import com.bjb.vr.common.mapper.ResContentMapper;
import com.bjb.vr.common.mapper.ResCusContentAuthorityMapper;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.ResCusContentAuthorityContVo;
import com.bjb.vr.common.vo.ResCusContentAuthorityDetailVo;
import com.bjb.vr.common.vo.ResCusContentAuthorityVo;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.github.yitter.idgen.YitIdHelper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author admin
* @description 针对表【res_cus_content_authority(客户内容授权表)】的数据库操作Service
* @createDate 2022-08-04 14:20:36
*/
@Slf4j
@Service
public class ResCusContentAuthorityService extends ServiceImpl<ResCusContentAuthorityMapper, ResCusContentAuthority> {


    @Autowired
    ResCusContentAuthorityMapper resCusContentAuthorityMapper;

    @Autowired
    ResContentAuthorityMapper resContentAuthorityMapper;

    @Autowired
    ResContentAuthorityService resContentAuthorityService;

    @Autowired
    ResPlatformResourceService resPlatformResourceService;

    @Autowired
    ResContentMapper resContentMapper;

    /**
     * 查询客户内容授权列表
     * @param resCusContentAuthorityAo
     * @return
     */
    public IPage<ResCusContentAuthorityVo> queryResCusContAuthorityPage(ResCusContentAuthorityAo resCusContentAuthorityAo){
            long current = (resCusContentAuthorityAo.getCurrent() - 1) * resCusContentAuthorityAo.getSize();
            List<ResCusContentAuthorityVo> resCusContentAuthorityList = resCusContentAuthorityMapper.
                    queryResCusContAuthorityPage(resCusContentAuthorityAo.getTenantName(),current,resCusContentAuthorityAo.getSize());
            long total = resCusContentAuthorityMapper.getResCusContAuthorityTotal(resCusContentAuthorityAo.getTenantName());
            IPage<ResCusContentAuthorityVo> voIPage = new Page<ResCusContentAuthorityVo>(resCusContentAuthorityAo.getCurrent(), resCusContentAuthorityAo.getSize(), total);
            voIPage.setRecords(resCusContentAuthorityList);
            return voIPage;
        }

    /**
     * 添加客户内容授权
      * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addResCusContentAuthority(ResCusContentAuthorityAo resCusContentAuthorityAo){

        // 换成自定义租户ID
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        umsAccountVo.setTempTenantId(resCusContentAuthorityAo.getTenantId());
        ResCusContentAuthority resCusContentAuthority = new ResCusContentAuthority();
        resCusContentAuthority.setTenantId(resCusContentAuthorityAo.getTenantId());
        resCusContentAuthority.setContValidStartDate(resCusContentAuthorityAo.getContValidStartDate());
        resCusContentAuthority.setContValidEndDate(resCusContentAuthorityAo.getContValidEndDate());
        resCusContentAuthority.setContValidDays(resCusContentAuthorityAo.getContValidDays());
        resCusContentAuthority.setGroupId(resCusContentAuthorityAo.getGroupId());
        if(resCusContentAuthorityAo.getContentIds()!=null && resCusContentAuthorityAo.getContentIds().length>0) {
            resCusContentAuthority.setResBundleIds(ArrayUtil.join(resCusContentAuthorityAo.getResBundleIds(), ","));
        }
        boolean result = this.save(resCusContentAuthority);
        if(result){
                List<ResContentAuthority> resContentAuthorityList = new ArrayList<>();
                StringBuffer stringBuffer = new StringBuffer("");
                for(String udid:resCusContentAuthorityAo.getUdids()) {
                    for (Long contentId : resCusContentAuthorityAo.getContentIds()) {
                        ResContentAuthority resContentAuthority = new ResContentAuthority();
                        resContentAuthority.setTenantId(resCusContentAuthorityAo.getTenantId());
                        resContentAuthority.setContentId(contentId);
                        resContentAuthority.setContValidStartDate(resCusContentAuthorityAo.getContValidStartDate());
                        resContentAuthority.setContValidEndDate(resCusContentAuthorityAo.getContValidEndDate());
                        resContentAuthority.setContValidDays(resCusContentAuthorityAo.getContValidDays());
                        resContentAuthority.setResCusContAuthId(resCusContentAuthority.getId());
                        resContentAuthority.setUdid(udid);
                        resContentAuthorityList.add(resContentAuthority);

                        LambdaQueryWrapper<ResContentAuthority> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(ResContentAuthority::getUdid,udid);
                        lambdaQueryWrapper.eq(ResContentAuthority::getContentId,contentId);
                        int count = resContentAuthorityMapper.selectCount(lambdaQueryWrapper);
                        if(count>0){
                            ResContent resContent =  resContentMapper.selectById(contentId);
                            stringBuffer.append(udid + ":" + resContent.getName());
                        }
                    }
                }
                if(!stringBuffer.toString().equals("")){
                    stringBuffer.append(" 已授权，本次资源授权失败！");
                    throw new CommonException(stringBuffer.toString());
                }

                resContentAuthorityService.saveBatch(resContentAuthorityList);
                result = resPlatformResourceService.addResPlatResourceByContentAuthority(resCusContentAuthorityAo.getContentIds(),resCusContentAuthorityAo.getTenantId());
        }

        return result;
    }

    /**
     * 修改客户内容授权
     * @param resCusContentAuthorityAo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateResCusContentAuthority(ResCusContentAuthorityAo resCusContentAuthorityAo){
        // 换成自定义租户ID
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        umsAccountVo.setTempTenantId(resCusContentAuthorityAo.getTenantId());

        ResCusContentAuthority resCusContentAuthority = new ResCusContentAuthority();
        resCusContentAuthority.setId(resCusContentAuthorityAo.getId());
        resCusContentAuthority.setTenantId(resCusContentAuthorityAo.getTenantId());
        resCusContentAuthority.setContValidStartDate(resCusContentAuthorityAo.getContValidStartDate());
        resCusContentAuthority.setContValidEndDate(resCusContentAuthorityAo.getContValidEndDate());
        resCusContentAuthority.setContValidDays(resCusContentAuthorityAo.getContValidDays());
        resCusContentAuthority.setGroupId(resCusContentAuthorityAo.getGroupId());
        if(resCusContentAuthorityAo.getContentIds()!=null && resCusContentAuthorityAo.getContentIds().length>0) {
            resCusContentAuthority.setResBundleIds(ArrayUtil.join(resCusContentAuthorityAo.getResBundleIds(), ","));
        }
        boolean result = this.updateById(resCusContentAuthority);

        if(result){
                //删除之前的授权记录
                LambdaQueryWrapper<ResContentAuthority> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(ResContentAuthority::getResCusContAuthId,resCusContentAuthorityAo.getId());
                resContentAuthorityMapper.delete(lambdaQueryWrapper);
                List<ResContentAuthority> resContentAuthorityList = new ArrayList<>();
                for(String udid:resCusContentAuthorityAo.getUdids()) {
                    for (Long contentId : resCusContentAuthorityAo.getContentIds()) {
                        ResContentAuthority resContentAuthority = new ResContentAuthority();
                        resContentAuthority.setTenantId(resCusContentAuthorityAo.getTenantId());
                        resContentAuthority.setContentId(contentId);
                        resContentAuthority.setContValidStartDate(resCusContentAuthorityAo.getContValidStartDate());
                        resContentAuthority.setContValidEndDate(resCusContentAuthorityAo.getContValidEndDate());
                        resContentAuthority.setContValidDays(resCusContentAuthorityAo.getContValidDays());
                        resContentAuthority.setResCusContAuthId(resCusContentAuthority.getId());
                        resContentAuthority.setUdid(udid);
                        resContentAuthorityList.add(resContentAuthority);
                    }
                }
                result = resContentAuthorityService.saveBatch(resContentAuthorityList);
            }
        umsAccountVo.setTempTenantId("");
        return result;
    }

    /**
     * 删除客户内容授权
     * 需求没有删除功能，暂时不实现
     * @param resCusContentAuthorityAo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteResCusContentAuthority(ResCusContentAuthorityAo resCusContentAuthorityAo){
        return false;
    }

    /**
     * 查询客户内容授权详情
     * @param resCusContentAuthorityAo
     * @return
     */
    public ResCusContentAuthorityVo queryResCusContentAuthorityDetail(ResCusContentAuthorityAo resCusContentAuthorityAo){

        ResCusContentAuthorityVo resCusContentAuthority = new ResCusContentAuthorityVo();
        ResCusContentAuthority  resCusContentAuthority1 = resCusContentAuthorityMapper.selectById(resCusContentAuthorityAo.getId());
        resCusContentAuthority.setTenantId(resCusContentAuthority1.getTenantId());
        resCusContentAuthority.setContValidStartDate(resCusContentAuthority1.getContValidStartDate());
        resCusContentAuthority.setContValidEndDate(resCusContentAuthority1.getContValidEndDate());
        resCusContentAuthority.setContValidDays(resCusContentAuthority1.getContValidDays());
        resCusContentAuthority.setGroupId(resCusContentAuthority1.getGroupId());
        resCusContentAuthority.setResBundleIds(resCusContentAuthority1.getResBundleIds());
        List<ResCusContentAuthorityContVo> resCusContentAuthorityContVoList = resContentAuthorityService.getAuthorityContentVoList(resCusContentAuthorityAo);
        resCusContentAuthority.setResCusContentAuthorityConVoList(resCusContentAuthorityContVoList);
        List<String> udidList = resContentAuthorityService.getAuthorityUdidList(resCusContentAuthorityAo);
        if(udidList!=null){
            resCusContentAuthority.setUdids(udidList.toArray(new String[udidList.size()]));
        }
        return resCusContentAuthority;
    }

}
